<?php


namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use \app\admin\model\department\Department as DepartmentModel;


class Department extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 初始化
     */
    public function department()
    {
        $department_id = $this->request->request('department_id');;
        $where = array(
            "parent_id" => $department_id
        );
        $xuexiao = model('app\admin\model\department\Department')
            ->where($where)
            ->order("id", "desc")
            ->select();
        // $department = $this->buildTree($xuexiao, 25); // 将 parentId 参数设置为 25
        $this->success('ok', $xuexiao);
    }

    /**
     * 党内职务
     */
    public function position()
    {
        $position = model('app\admin\model\department\Position')
            ->order("id", "desc")
            ->select();
        $this->success('ok', $position);
    }

    /**
     * 构建树结构
     */
    public function buildTree($data, $parentId = 0)
    {
        // 按照 parent_id 分组数据
        $grouped = [];
        foreach ($data as $item) {
            $grouped[$item['parent_id']][] = $item;
        }
        // 递归构建树结构
        return $this->buildTreeRecursive($grouped, $parentId);
    }

    /**
     * 递归构建树
     */
    private function buildTreeRecursive($grouped, $parentId)
    {
        $tree = [];
        if (!isset($grouped[$parentId])) {
            return $tree;
        }

        foreach ($grouped[$parentId] as $item) {
            $item['children'] = $this->buildTreeRecursive($grouped, $item['id']);
            $tree[] = $item;
        }
        return $tree;
    }





    /**
     * 学校列表
     */
    public function school()
    {
        $department_id = $this->request->request('department_id');
        $where = array(
            "parent_id" => $department_id
        );
        $xuexiao = model('app\admin\model\department\School')
            ->where($where)
            ->order("id", "desc")
            ->select();
        // $department = $this->buildTree($xuexiao, 25); // 将 parentId 参数设置为 25
        $this->success('ok', $xuexiao);
    }
}
